package com.bw.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.lib_mvicore.model.BaseModel
import com.bw.lib_net.entity.ResponseEntity
import com.bw.module_home.intent.FocusIntent
import com.bw.module_home.model.entity.FocusEntity
import com.bw.module_home.model.service.FocusService
import com.bw.module_home.state.FocusState
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/30 09:14
 * @Description :
 */
class FocusViewModel: BaseModel<FocusIntent>() {

    val service: FocusService by lazy { FocusService() }
    private val _state = MutableStateFlow<FocusState>(FocusState.Init)
    val state: StateFlow<FocusState> = _state.asStateFlow()

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {
                    is FocusIntent.Focus -> {
                        doFocuse(it)
                    }
                }
            }
        }
    }

    private fun doFocuse(focuseIntent: FocusIntent.Focus) {
        viewModelScope.launch {
            flow<ResponseEntity<FocusEntity>> {
                val data = service.focuse(focuseIntent.focuseUserid, focuseIntent.focusedUserid)
                emit(data)
            }.catch {
                _state.value=FocusState.FocuseFailed(focuseIntent.position)
            }.filter {
                it != null
            }.collect{
                if (it != null&&it.code==0){
                    _state.value=FocusState.FocuseSuccess(it.data)
                }else{
                    _state.value=FocusState.FocuseFailed(focuseIntent.position)
                }
            }
        }
    }
}